package com.ioidea.holland.greenHouseAct


import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.widget.Toast
import com.ioidea.base.util.MyLogger
import com.ioidea.holland.R


class GreenHouse(context: Context, attrs: AttributeSet? = null) : View(context, attrs) {

    private var lastMoveTime: Long=0

    //绘制矩形的笔
    private val paint = Paint()

    //绘制文字的笔
    private val textPaint = Paint()

    //矩形点集合
    private val points = ArrayList<Point>()
    private val spacing = 10  // 间距的大小，你可以根据需要调整

    private var lastTouchY = 0f
    private var translateY = 0f

    private var lastTouchX = 0f
    private var translateX = 0f

    //x轴滑动边界
    private var minX = 0
    private var maxX = 1000

    //y轴滑动边界
    private var minY = 0
    private var maxY = 1000

    //矩形设备的宽高
    var rectWidth = 0
    var rectHeight = 0

    //点击阀值
    var clickThreshold = 40

    init {
        paint.color = Color.GREEN
        paint.style = Paint.Style.FILL

        textPaint.color = Color.BLACK
        textPaint.textSize = dpToPx(14).toFloat()

        rectWidth = dpToPx(50) // 每个矩形的宽度
        rectHeight = dpToPx(50)  // 每个矩形的高度
    }

    fun setPoints(points: List<Point>) {
        this.points.clear()
        this.points.addAll(points)
        setBorder()
        invalidate()
    }

    /**
     * 设置边界
     */
    private fun setBorder() {
        maxX = (maxColumn - 1) * (rectWidth + dpToPx(spacing)) + rectWidth
        maxY = (maxRow - 1) * (rectHeight + dpToPx(spacing)) + rectHeight
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
//        setBackgroundColor(resources.getColor(R.color.color_0B))
    }
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        for (point in points) {
            val left = (point.column - 1) * (rectWidth + dpToPx(spacing))  // 计算矩形的左边距
            val top = (point.row - 1) * (rectHeight + dpToPx(spacing))
            val right = left + rectWidth  // 计算矩形的右边距
            val bottom = top + rectHeight  // 计算矩形的下边距

            canvas.drawRect(left.toFloat(), top.toFloat(), right.toFloat(), bottom.toFloat(), paint)

            drawText(canvas, point, left, top, right, bottom)

        }


    }

    private fun drawText(
        canvas: Canvas,
        point: Point,
        left: Int,
        top: Int,
        right: Int,
        bottom: Int
    ) {
        // 计算矩形中心点坐标
        val centerX = (left + right) / 2f
        val centerY = (top + bottom) / 2f
        // 绘制文字
        val text = "${point.row},${point.column}"

        val textBounds = Rect()
        textPaint.getTextBounds(text, 0, text.length, textBounds)
        val textX = centerX - textBounds.exactCenterX()
        val textY = centerY - textBounds.exactCenterY()
        canvas.drawText(text, textX, textY, textPaint)
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                lastTouchY = event.y
                lastTouchX = event.x

            }

            MotionEvent.ACTION_MOVE -> {
                var deltaY = event.y - lastTouchY
                //判断滑动方向
                var deltaX = event.x - lastTouchX


//                val currentTime = System.currentTimeMillis()
//                val deltaTime = currentTime - lastMoveTime
//
//
//                if (deltaTime > 0) {
//                    val speedX = deltaX / deltaTime
//                    val speedY = deltaY / deltaTime
//
//                    // 限制速度，可以根据需要调整这些值
//                    val maxSpeed = 10.0f
//                    if (speedX > maxSpeed) {
//                        deltaX = maxSpeed * deltaTime
//                    }
//                    if (speedX < -maxSpeed) {
//                        deltaX = -maxSpeed * deltaTime
//                    }
//                    if (speedY > maxSpeed) {
//                        deltaY = maxSpeed * deltaTime
//                    }
//                    if (speedY < -maxSpeed) {
//                        deltaY = -maxSpeed * deltaTime
//                    }
//                }
//
//                lastMoveTime = currentTime
//                lastMoveX = event.x
//                lastMoveY = event.y
                
                
                
                

                // 计算滑动距离的绝对值
//                val distance = Math.sqrt((deltaX * deltaX + deltaY * deltaY).toDouble())

//                if (distance > clickThreshold) {
                    // 如果滑动距离超过阈值，将其解释为滑动操作

                    handleSlideEvent(event,deltaX, deltaY)
//                } else {
//                    handleClickEvent(deltaX,deltaY)
//
//
//                }
            }
        }
        return true
    }

    private fun handleSlideEvent(event: MotionEvent, deltaX: Float, deltaY: Float) {
        MyLogger.hLog().e("==============x轴数据=============================")
        MyLogger.hLog().i("lastTouchX:${lastTouchX}")
        MyLogger.hLog().i("event.x:${event.x}")
        MyLogger.hLog().i("deltaX:${deltaX.toInt()}")

        MyLogger.hLog().e("==============y轴数据=============================")
        MyLogger.hLog().i("lastTouchY:${lastTouchY}")
        MyLogger.hLog().i("event.y:${event.y}")
        MyLogger.hLog().i("-deltaY:${-deltaY.toInt()}")

        lastTouchY = event.y
        lastTouchX = event.x
        MyLogger.hLog()
            .e("==============滑动的具体坐标位置=============================")
        MyLogger.hLog().i("scrollX:${scrollX}")
        MyLogger.hLog().i("scrollY:${scrollY}")
        var newDeltaX = deltaX
        var newDeltaY = deltaY

        if (-deltaX >= 0 && scrollX + width + deltaX >= maxX) {
            //向有滚动，超出x轴边界时滑动0
            newDeltaX = 0.0f
        } else if (-deltaX < 0 && scrollX  <= minX) {
            newDeltaX = 0.0f
        }

        if (-deltaY >= 0 && scrollY + height + deltaY >= maxY) {
            //向下滑动
            newDeltaY = 0.0f
        } else if (-deltaY < 0 && scrollY  <= minY) {
            //向上滑动
            newDeltaY = 0.0f
        }
        scrollBy(-newDeltaX.toInt(), -newDeltaY.toInt())  // 使用scrollBy滚动

    }


    private fun handleClickEvent(deltaX: Float, deltaY: Float) {
        for (point in points) {
            val left = (point.column - 1) * (rectWidth + dpToPx(spacing))
            val top = (point.row - 1) * (rectHeight + dpToPx(spacing))
            val right = left + rectWidth
            val bottom = top + rectHeight

            if (scrollX + lastTouchX >= left && scrollX + lastTouchX <= right && scrollY + lastTouchY >= top && scrollY + lastTouchY <= bottom) {
                // 触摸点在矩形内，执行点击操作
                handleRectangleClick(point)
//                        return true
            }
        }

    }

    private fun handleRectangleClick(point: Point) {
        // 在这里处理矩形的点击事件，你可以执行任何你需要的操作
        // 例如，显示相关信息或执行其他操作
        // point 是被点击的矩形的坐标信息
        MyLogger.hLog().e(point)
        Toast.makeText(context, point.toString(), Toast.LENGTH_SHORT).show()
    }

    private val maxRow: Int
        get() {
            return points.maxByOrNull { it.row }?.row ?: 1
        }

    private val maxColumn: Int
        get() {
            return points.maxByOrNull { it.column }?.column ?: 1
        }

    fun dpToPx(dpValue: Int): Int {
        val density = resources.displayMetrics.density
        val pxValue = (dpValue * density + 0.5f).toInt()
        return pxValue
    }


}